#include "StdAfx.h"
#include "GoHome.h"
#include "Dead.h"
#include "Thirsty.h"
#include "myRand.h"
#include "Ant.h"
#include "terrain.h"

extern int terrain[kMaxRows][kMaxCols];
extern CAnt antList[kMaxAnts];

CGoHome * CGoHome::instance()
{
	static CGoHome inst;
	return (&inst);
}

void CGoHome::Enter(CAnt *pAnt)
{
}

void CGoHome::Execute(CAnt *pAnt)
{
	int rowMove, colMove;
	int newRow, newCol;
	int homeRow, homeCol;
	int poisonRow, poisonCol;

	if(pAnt->type == kRedAnt){
		homeRow = kRedHomeRow;
		homeCol = kRedHomeCol;
	}
	else{
		homeRow = kBlackHomeRow;
		homeCol = kBlackHomeCol;
	}
	if(pAnt->row < homeRow) rowMove = 1;
	else if(pAnt->row > homeRow) rowMove = -1;
	else rowMove = 0;

	if(pAnt->col < homeCol) colMove = 1;
	else if(pAnt->col > homeCol) colMove = -1;
	else colMove = 0;

	newRow = pAnt->row + rowMove;
	newCol = pAnt->col + colMove;

	if(newRow < 1) return;
	if(newCol < 1) return;
	if(newRow >= kMaxRows-1) return;
	if(newCol >= kMaxCols-1) return;

	if(terrain[newRow][newCol] != kPoison){
		pAnt->row = newRow;
		pAnt->col = newCol;
	}
	else{
		pAnt->row = newRow;
		pAnt->col = newCol;
		terrain[newRow][newCol] = kGround;
		do{
			poisonRow = rnd(0, kMaxRows-1);
			poisonCol = rnd(0, kMaxCols-1);
		}while(terrain[poisonRow][poisonCol] != kGround);
		terrain[poisonRow][poisonCol] = kPoison;
		pAnt->changeState(CDead::instance());
	}
	if(newRow == homeRow && newCol == homeCol) {
		pAnt->row = newRow;
		pAnt->col = newCol;
		for(int i=0; i<kMaxAnts; i++){
			if(antList[i].type == 0){
				antList[i].New(pAnt->type, homeRow, homeCol);
				CAnt::antNum++;
				break;
			}
		}
		pAnt->changeState(CThirsty::instance());
	}
}

void CGoHome::Exit(CAnt *pAnt)
{
}